package com.ruiysoft.controller.integral;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruiysoft.controller.integral.vo.IntegralListVo;
import com.ruiysoft.controller.integral.vo.IntegralRechargeVo;
import com.ruiysoft.controller.integral.vo.IntegralTradeListVo;
import com.ruiysoft.entity.integral.Integral;
import com.ruiysoft.entity.integral.IntegralCurrent;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.pub.entity.PageInfo;
import com.ruiysoft.service.integral.IIntegralCurrentService;
import com.ruiysoft.service.integral.IIntegralService;
import com.ruiysoft.service.integral.bean.IntegralCondition;
import com.ruiysoft.service.integral.consts.TradeType;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-04-13T19:28:15.988+08:00")

@RestController
public class IntegralApiController implements IntegralApi {

    private static final Logger log = LoggerFactory.getLogger(IntegralApiController.class);


    private final IIntegralService integralService;
    private final IIntegralCurrentService integralCurrentService;

    @org.springframework.beans.factory.annotation.Autowired
    public IntegralApiController(IIntegralService integralService, IIntegralCurrentService integralCurrentService) {
        this.integralService = integralService;
        this.integralCurrentService = integralCurrentService;
    }
    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }
    @Override
    public Result<PageInfo> integralListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "手机号") @Valid @RequestParam(value = "phone", required = false) String phone) {
        Long shopId = getShopId();
//        SysShopPersonnel personnel = getUser();
        IntegralCondition condition = new IntegralCondition()
                .setShopId(shopId).setPhone(phone).setSuperOrderByClause("update_time desc");
        try {
            IPage<Integral> page = integralService.page(new Page<>(pageStart,pageSize),integralService.getWapperByCondition(condition));
            List<IntegralListVo> list = page.getRecords().stream().filter(Objects::nonNull)
                    .map(a->new IntegralListVo().integralId(a.getId()).integral(a.getIntegral())
                            .tradeTime(Optional.ofNullable(a.getUpdateTime()).map(Date::getTime).orElse(null))
                            .phone(a.getPhone())
                    ).collect(Collectors.toList());

            return ResultGenerator.genSuccessResult(new PageInfo<IntegralListVo>(list, (Page) page));
        } catch (Exception e) {
            log.error("查询积分余额列表--{}", JSONObject.toJSONString(condition), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> integralRechargePost(@ApiParam(value = ""  )  @Valid @RequestBody List<IntegralRechargeVo> list) {
//        integralService.rechargeList(list);
        Long shopId = getShopId();
        if(list==null||list.isEmpty()){
            throw new RuntimeException("没有要充值的记录");
        }
        list.stream().filter(Objects::nonNull).forEach(recharge->integralService.recharge(recharge,shopId));
        return ResultGenerator.genSuccessResult();
    }

    @Override
    public Result<PageInfo> integralTradeListGet(@NotNull @ApiParam(value = "分页开始页", required = true) @Valid @RequestParam(value = "pageStart", required = true) Integer pageStart, @NotNull @ApiParam(value = "每页显示多少条数据", required = true) @Valid @RequestParam(value = "pageSize", required = true) Integer pageSize, @ApiParam(value = "开始时间（时间戳）") @Valid @RequestParam(value = "sTime", required = false) Long sTime, @ApiParam(value = "结束时间（时间戳）") @Valid @RequestParam(value = "eTime", required = false) Long eTime, @ApiParam(value = "积分余额id") @Valid @RequestParam(value = "integralId", required = false) Long integralId, @ApiParam(value = "手机号") @Valid @RequestParam(value = "phone", required = false) String phone, @ApiParam(value = "交易类型（1，充值，2，消费，3，退款）") @Valid @RequestParam(value = "tradeType", required = false) Integer tradeType) {
        Long shopId = getShopId();
        IntegralCondition condition = new IntegralCondition()
                .setShopId(shopId).setIntegralId(integralId)
                .setTradeType(Optional.ofNullable(TradeType.getEnum(tradeType)).orElse(null))
                .setsTime(Optional.ofNullable(sTime).map(a->new Date(a)).orElse(null))
                .seteTime(Optional.ofNullable(eTime).map(a->new Date(a)).orElse(null))
                .setSuperOrderByClause("createtime desc");
        try {
            IPage<IntegralCurrent> page = integralCurrentService.page(new Page<>(pageStart,pageSize),integralCurrentService.getWapperByCondition(condition));
            List<IntegralTradeListVo> list = page.getRecords().stream().filter(Objects::nonNull)
                    .map(a->new IntegralTradeListVo().id(a.getId()).integral(a.getIntegral()).phone(a.getPhone())
                            .tradeTime(Optional.ofNullable(a.getCreatetime()).map(Date::getTime).orElse(null))
                            .tradeType(a.getTradeType())
                            .typeName(Optional.ofNullable(TradeType.getEnum(a.getTradeType())).map(TradeType::getName).orElse(""))
                    ).collect(Collectors.toList());
            return ResultGenerator.genSuccessResult(new PageInfo<IntegralTradeListVo>(list, (Page) page));
        } catch (Exception e) {
            log.error("用户查询积分记录--{}", JSONObject.toJSONString(condition), e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

}
